// 默认设置
const defaultSettings = {
  apiPlatform: 'aliyun',
  baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
  apiKey: '',
  chatModel: 'qwq-32b',
  embeddingModel: 'text-embedding-v2'
};

// 平台默认URL
const platformDefaults = {
  aliyun: {
    baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
    chatModel: 'qwq-32b',
    embeddingModel: 'text-embedding-v2'
  },
  guiji: {
    baseUrl: 'https://api.siliconflow.cn/v1',
    chatModel: 'Qwen/Qwen2.5-72B-Instruct',
    embeddingModel: 'embedding-2'
  },
  openai: {
    baseUrl: 'https://api.openai.com/v1',
    chatModel: 'gpt-3.5-turbo',
    embeddingModel: 'text-embedding-3-small'
  }
};

// 页面元素
const platformSelect = document.getElementById('api-platform');
const baseUrlInput = document.getElementById('api-base-url');
const apiKeyInput = document.getElementById('api-key');
const chatModelSelect = document.getElementById('chat-model');
const embeddingModelSelect = document.getElementById('embedding-model');
const saveButton = document.getElementById('save-settings');
const testButton = document.getElementById('test-connection');
const statusMessage = document.getElementById('status-message');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
  loadSettings();
  setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
  // 平台切换
  platformSelect.addEventListener('change', () => {
    const platform = platformSelect.value;
    updatePlatformDefaults(platform);
  });

  // 保存设置
  saveButton.addEventListener('click', saveSettings);

  // 测试连接
  testButton.addEventListener('click', testConnection);
}

// 根据选择的平台更新默认值
function updatePlatformDefaults(platform) {
  const defaults = platformDefaults[platform];
  baseUrlInput.value = defaults.baseUrl;
  
  // 更新对话模型选择器
  const chatOptions = chatModelSelect.querySelectorAll('option');
  let foundMatch = false;
  
  chatOptions.forEach(option => {
    const optgroup = option.closest('optgroup');
    if (optgroup && optgroup.label.includes(getPlatformLabel(platform))) {
      if (!foundMatch) {
        option.selected = true;
        foundMatch = true;
      }
    }
  });
  
  // 更新嵌入模型选择器
  const embeddingOptions = embeddingModelSelect.querySelectorAll('option');
  foundMatch = false;
  
  embeddingOptions.forEach(option => {
    const optgroup = option.closest('optgroup');
    if (optgroup && optgroup.label.includes(getPlatformLabel(platform))) {
      if (!foundMatch) {
        option.selected = true;
        foundMatch = true;
      }
    }
  });
}

// 获取平台显示名称
function getPlatformLabel(platform) {
  switch (platform) {
    case 'aliyun': return '阿里云';
    case 'guiji': return '硅基流';
    case 'openai': return 'OpenAI';
    default: return '';
  }
}

// 从存储中加载设置
function loadSettings() {
  chrome.storage.local.get('apiSettings', (result) => {
    const settings = result.apiSettings || defaultSettings;
    
    // 设置表单值
    platformSelect.value = settings.apiPlatform;
    baseUrlInput.value = settings.baseUrl || platformDefaults[settings.apiPlatform].baseUrl;
    apiKeyInput.value = settings.apiKey || '';
    
    // 设置模型选择
    if (settings.chatModel) {
      const chatOptions = chatModelSelect.querySelectorAll('option');
      chatOptions.forEach(option => {
        if (option.value === settings.chatModel) {
          option.selected = true;
        }
      });
    }
    
    if (settings.embeddingModel) {
      const embeddingOptions = embeddingModelSelect.querySelectorAll('option');
      embeddingOptions.forEach(option => {
        if (option.value === settings.embeddingModel) {
          option.selected = true;
        }
      });
    }
  });
}

// 保存设置到存储
function saveSettings() {
  const apiPlatform = document.getElementById('api-platform').value;
  const baseUrl = document.getElementById('api-base-url').value.trim();
  const apiKey = document.getElementById('api-key').value.trim();
  const chatModel = document.getElementById('chat-model').value;
  const embeddingModel = document.getElementById('embedding-model').value;
  
  if (!baseUrl || !apiKey) {
    showStatus('请填写API基础URL和API Key', 'error');
    return;
  }
  
  // 获取现有设置以检查嵌入模型是否更改
  chrome.storage.local.get('apiSettings', (result) => {
    const oldSettings = result.apiSettings || {};
    const embeddingModelChanged = oldSettings.embeddingModel && 
                                 oldSettings.embeddingModel !== embeddingModel;
    
    // 新设置
    const newSettings = {
      apiPlatform,
      baseUrl,
      apiKey,
      chatModel,
      embeddingModel
    };
    
    // 如果嵌入模型更改，提示用户
    if (embeddingModelChanged) {
      if (confirm('您更改了嵌入模型，这将影响语义搜索功能。需要为所有已保存的提示词重新计算向量吗？')) {
        // 保存设置并标记需要重新计算向量
        chrome.storage.local.set({
          apiSettings: newSettings,
          needRecalculateVectors: true
        }, () => {
          showStatus('设置已保存，将在下次打开扩展时重新计算向量', 'success');
        });
      } else {
        // 仅保存设置
        chrome.storage.local.set({
          apiSettings: newSettings
        }, () => {
          showStatus('设置已保存，但不会重新计算向量', 'success');
        });
      }
    } else {
      // 嵌入模型未更改，直接保存设置
      chrome.storage.local.set({
        apiSettings: newSettings
      }, () => {
        showStatus('设置已保存', 'success');
      });
    }
  });
}

// 测试API连接
async function testConnection() {
  showStatus('正在测试连接...', '');
  
  const platform = platformSelect.value;
  const baseUrl = baseUrlInput.value;
  const apiKey = apiKeyInput.value;
  
  if (!baseUrl || !apiKey) {
    showStatus('API基础URL和API Key不能为空', 'error');
    return;
  }
  
  try {
    // 测试连接
    const isConnected = await testApiConnection(platform, baseUrl, apiKey);
    showStatus('连接成功！API有效', 'success');
  } catch (error) {
    showStatus(`连接失败: ${error.message}`, 'error');
  }
}

// 测试API连接
async function testApiConnection(platform, baseUrl, apiKey) {
  // 实际应用中可以尝试发送一个小请求来验证API是否可用
  // 例如获取模型列表或发送一个简单的请求
  
  // 在这里我们只是简单检查API Key是否存在
  if (!apiKey) {
    throw new Error('API Key不能为空');
  }
  
  // 模拟连接成功
  return true;
}

// 显示状态消息
function showStatus(message, type) {
  statusMessage.textContent = message;
  statusMessage.className = 'status-message';
  
  if (type) {
    statusMessage.classList.add(type);
  }
  
  if (type === 'success') {
    setTimeout(() => {
      statusMessage.textContent = '';
    }, 3000);
  }
} 